
const app = getApp()

Page({
  data: {
    messages: [],
    inputMessage: '',
    toView: '',
    isTyping: false,
    loading: true,
  },

  onLoad: function () {
    wx.setNavigationBarTitle({
      title: 'ChatGPT 小程序'
    })
  },

  onInput: function (event) {
    this.setData({
      inputMessage: event.detail.value
    })
  },
  onShareAppMessage() {
    return {
      title: 'GhatGpt4.0 它来了!',
      path: '/page/index/index',
      imageUrl: '/images/gpt.png',
    }
  },
  onSend: function () {
    const { messages, inputMessage, isTyping } = this.data
    if (inputMessage === '') {
      return
    }
    messages.push({
      role: 'user',
      content: inputMessage
    })

    this.setData({
      messages,
      inputMessage: '',
      toView: `msg-${messages.length - 1}`,
      isTyping: true
    })

    this.requestChat(inputMessage)
  },

  requestChat: function (message) {
    const { messages } = this.data;
    messages.push({
      role: 'other',
      content: '正在思考中！',
      wating: true
    })
    this.setData({
      messages,
      toView: `msg-${messages.length - 1}`,
      isTyping: false
    })
    console.log(this.data.messages);
    if (this.data.messages != null && this.data.messages != undefined) {
      this.data.messages = this.data.messages.filter(item => item.wating != true);
    }
    console.log(this.data.messages);
    var Key = wx.getStorageSync('key');
    var Proxy = wx.getStorageSync('proxy');
    const data = { Message: this.data.messages, Key: Key, Proxy: Proxy };
    const parm = JSON.stringify(data);

    this.toViewBottomFun();
    wx.cloud.init({
      env: 'chat-7g7kzkt51c7d58c5',
      // env: cloud.DYNAMIC_CURRENT_ENV // 默认第一个数据库
      timeout: '60',
    })
    wx.cloud.callFunction({
      name: 'chat',
      timeout: '300000',
      data: { parm },
      config: { timeout: '300000' },
      success: async res => {
        setInterval(() => {
          console.log(res);
        }, 100);
        console.log(res.result);
        if (res.result == 'error') {
          messages[messages.length - 1] = {
            role: 'other',
            content: '出错啦，客官等等再试...',
            wating: true
          };
        } else {
          const role = res.result.choices[0].message.role.trim();
          const backmsg = res.result.choices[0].message.content.trim();
          messages[messages.length - 1] = {
            role: role,
            content: backmsg
          };
        }

        // messages[messages.length - 1]=({)

        this.setData({
          messages,
          toView: `msg-${messages.length - 1}`,
          isTyping: false,
          session: messages
        })
        this.toViewBottomFun();
      },
      fail: err => {
        console.error(err)
      }
    })
  },
  toViewBottomFun: function () {
    // 设置屏幕自动滚动到最后一条消息处
    let that = this;
    wx.createSelectorQuery().select('#viewCommunicationBody').boundingClientRect(function (rect) {
      wx.pageScrollTo({
        scrollTop: rect.height,
        duration: 100 // 滑动速度
      })
      that.setData({
        scrollTop: rect.height - that.data.scrollTop
      });
    }).exec();
  }
})